import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

//TCP客服端
public class TcpEchoServer {
    public Socket socket = null;

    public TcpEchoServer() throws IOException {
        //创建对象和服务器建立连接
        socket = new Socket("127.0.0.1",2000);
    }

    public void stack() throws IOException {
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanNext = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while(true) {
                //从控制台读取请求
                System.out.printf(">:");
                String str = scanner.next();
                //发送请求
                printWriter.println(str);
                printWriter.flush();
                //读取响应数据
                String str1 = scanNext.next();
                //打印请求响应信息
                System.out.printf("[%s:%d] 请求:%s 响应:%s\n",socket.getInetAddress().toString(),socket.getPort(),str,str1);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer();
        server.stack();
    }
}
